import Cesium from './CesiumModule';
import { viewerObj } from './CesiumModule';

//===== 测量工具条部分！！！=====//

// 存储测量产生的实体
let measureEntity = [];
const imgValues = []
const toolClick = (tool, e) => {
  // 清除测量产生的实体
  measureEntity.forEach((item) => {
    viewerObj.viewer.entities.remove(item);
  });
  if (tool == 1) {
    // 测量距离
    let distance = 0;
    let positions = [];
    let poly = null;
    let distanceLable = null;
    let handler = new Cesium.ScreenSpaceEventHandler(viewerObj.viewer.scene.canvas);
    // 鼠标移动
    handler.setInputAction((movement) => {
      let cartesian = viewerObj.viewer.scene.camera.pickEllipsoid(movement.endPosition, viewerObj.viewer.scene.globe.ellipsoid);
      // 只有在点击之后移动才会生效
      if (positions.length >= 2) {
        // Cesium.defined()方法用于检测一个对象是否被定义了，如果被定义了，返回true，否则返回false
        if (!Cesium.defined(poly)) {
          poly = new PolylinePrimitive(positions);
        } else {
          positions.pop();
          positions.push(cartesian);
        }
        distance = getSpaceDistance(positions);
        if (!Cesium.defined(distanceLable)) {
          distanceLable = new DistanceLable(positions[positions.length - 1], distance);
        } else {
          distanceLable.show = true;
          distanceLable.position = positions[positions.length - 1];
          distanceLable.text = distance + '米';
        }
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    // 鼠标左键点击
    handler.setInputAction((movement) => {
      // cartesian是鼠标点击的位置
      let cartesian = viewerObj.viewer.scene.camera.pickEllipsoid(movement.position, viewerObj.viewer.scene.globe.ellipsoid);
      if (cartesian) {
        // 鼠标左键点击
        if (positions.length == 0) {
          // cartesian.clone()是为了防止positions数组中的元素是同一个对象
          positions.push(cartesian.clone());
        }
        // 这是终点，暂时与起点相同
        positions.push(cartesian);
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    // 鼠标右键点击
    handler.setInputAction((movement) => {
      handler.destroy();
      distanceLable.show = false;
      poly.show = false;
      positions = [];
      distance = 0;
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    // 绘制距离标签
    class DistanceLable {
      constructor(position, text) {
        this.options = {
          name: '距离标签',
          position: position,
          label: {
            show: true,
            text: text,
            font: '18px sans-serif',
            fillColor: Cesium.Color.CHARTREUSE,
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            outlineWidth: 2,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            pixelOffset: new Cesium.Cartesian2(20, -20),
          },
        };
        this._init();
      }
      _init() {
        this.options.position = new Cesium.CallbackProperty((time, result) => {
          return this.position;
        }, false);
        this.options.label.text = new Cesium.CallbackProperty((time, result) => {
          return this.text;
        }, false);
        measureEntity.push(viewerObj.viewer.entities.add(this.options));
      }
    }
    // 定义线的构造函数
    class PolylinePrimitive {
      constructor(positions) {
        this.options = {
          name: '线',
          polyline: {
            show: true,
            positions: [],
            material: Cesium.Color.CHARTREUSE,
            width: 5,
            clampToGround: true,
          },
        };
        this.positions = positions;
        this._init();
      }
      _init() {
        let _self = this;
        let _update = function () {
          // 返回polyline.positions的值，用箭头函数的话，this就不用起别名了
          return _self.positions;
        };
        // 实时更新polyline.positions,并不是每次都重新生成一个新的polyline，而是给的位置就是动态的
        this.options.polyline.positions = new Cesium.CallbackProperty(_update, false);
        measureEntity.push(viewerObj.viewer.entities.add(this.options));
      }
    }
    // 计算两点之间的距离
    function getSpaceDistance(positions) {
      let distance = 0;
      for (let i = 0; i < positions.length - 1; i++) {
        let point1cartographic = Cesium.Cartographic.fromCartesian(positions[i]);
        let point2cartographic = Cesium.Cartographic.fromCartesian(positions[i + 1]);
        /**
         * 根据经纬度计算出距离
         * @param {Object} point1
         * @param {Object} point2
         */
        let geodesic = new Cesium.EllipsoidGeodesic();
        geodesic.setEndPoints(point1cartographic, point2cartographic);
        let s = geodesic.surfaceDistance;
        distance += s;
      }
      return distance.toFixed(2);
    }

  }
}

export { toolClick, imgValues }